<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <title>部门管理 - xx管理系统</title>

  <!-- Favicons -->
  <link href="assets/img/favicon.png" rel="icon">

  <!-- Vendor CSS Files -->
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="assets/vendor/gridjs/dist/theme/mermaid.min.css" rel="stylesheet">

  <!-- Template Main CSS File -->
  <link href="assets/css/style.css" rel="stylesheet">
</head>

<body>

  <!-- ======= Header ======= -->
  <header id="header" class="header fixed-top d-flex align-items-center">
    <div class="d-flex align-items-center justify-content-between">
      <a href="index.html" class="logo d-flex align-items-center">
        <img src="assets/img/logo.png" alt="">
        <span class="d-none d-lg-block">XX管理系统</span>
      </a>
      <i class="bi bi-list toggle-sidebar-btn"></i>
    </div>

    <nav class="header-nav ms-auto">
      <ul class="d-flex align-items-center">
        <li class="nav-item dropdown pe-3">
          <a class="nav-link nav-profile d-flex align-items-center pe-0" href="#" data-bs-toggle="dropdown">
            <img src="assets/img/profile-img.jpg" alt="Profile" class="rounded-circle">
            <span class="d-none d-md-block dropdown-toggle ps-2">用户名</span>
          </a>
          <ul class="dropdown-menu dropdown-menu-end dropdown-menu-arrow profile">
            <li class="dropdown-header">
              <h6>部门名</h6>
              <span>角色名</span>
            </li>
            <li>
              <hr class="dropdown-divider">
            </li>
            <li>
              <a class="dropdown-item d-flex align-items-center" href="personal.html">
                <i class="bi bi-gear"></i>
                <span>个人信息</span>
              </a>
            </li>
            <li>
              <hr class="dropdown-divider">
            </li>
            <li>
              <a class="dropdown-item d-flex align-items-center" href="#">
                <i class="bi bi-box-arrow-right"></i>
                <span>注销登录</span>
              </a>
            </li>
          </ul>
        </li>
      </ul>
    </nav>
  </header>

  <!-- ======= Sidebar ======= -->
  <aside id="sidebar" class="sidebar">
    <ul class="sidebar-nav" id="sidebar-nav">
      <li class="nav-item">
        <a class="nav-link collapsed" href="index.html">
          <i class="bi bi-grid"></i>
          <span>个人主页</span>
        </a>
      </li>

      <li class="nav-item">
        <a class="nav-link" data-bs-target="#components-nav" data-bs-toggle="collapse" href="#">
          <i class="bi bi-menu-button-wide"></i><span>系统管理</span><i class="bi bi-chevron-down ms-auto"></i>
        </a>
        <ul id="components-nav" class="nav-content" data-bs-parent="#sidebar-nav">
          <li><a href="system-user.html"><i class="bi bi-circle"></i><span>用户管理</span></a></li>
          <li><a href="system-dept.html" class="active"><i class="bi bi-circle"></i><span>部门管理</span></a></li>
          <li><a href="system-role.html"><i class="bi bi-circle"></i><span>角色管理</span></a></li>
        </ul>
      </li>

      <li class="nav-item">
        <a class="nav-link collapsed" href="blank.html">
          <i class="bi bi-file-earmark"></i>
          <span>空白模板页</span>
        </a>
      </li>
    </ul>
  </aside>

  <main id="main" class="main">
    <div class="pagetitle">
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="index.html">主页</a></li>
          <li class="breadcrumb-item">系统管理</li>
          <li class="breadcrumb-item active">部门管理</li>
        </ol>
      </nav>
    </div>

    <section class="section">
      <div class="row">
        <div class="col-lg-12">
          <div class="card">
            <div class="card-body">
              <h5 class="card-title">部门列表</h5>
              <form id="searchForm" class="row row-cols-lg-auto g-3 mb-3 align-items-center">
                <div class="col-12">
                  <input type="text" class="form-control" name="name" placeholder="部门名称" />
                </div>
                <div class="col-12">
                  <button type="submit" class="btn btn-primary"><i class="bi bi-search"></i>查询</button>
                  <button type="reset" class="btn btn-secondary"><i class="bi bi-arrow-repeat"></i>重置</button>
                  <button id="createdeptButton" type="button" class="btn btn-success"><i
                      class="bi bi-plus"></i>添加</button>
                </div>
              </form>
              <div id="dataTable"></div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </main>

  <!-- Footer -->
  <footer id="footer" class="footer">
    <div class="credits">Designed by 2022030202033-曾广生</div>
  </footer>

  <!-- Success Toast -->
  <div class="toast-container position-absolute top-0 end-0">
    <div id="successToastEl" class="toast hide" role="alert" aria-live="assertive" aria-atomic="true"
      style="color: #fff;background-color: #19875488;">
      <div class="toast-body"><i class="bi bi-check-circle"></i><span id="successMessage">操作成功！</span></div>
    </div>
  </div>

  <!-- Edit Modal -->
  <div class="modal fade" id="editdeptModalEl" tabindex="-1" aria-hidden="true">
    <form id="editdeptForm" class="needs-validation" novalidate>
      <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">编辑部门</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>

          <div class="modal-body">
            <div id="editdeptAlert"></div>
            <div class="mb-3">
              <label for="id" class="form-label">编号</label>
              <input type="text" class="form-control" id="id" name="id" required />
            </div>
            <div class="mb-3">
              <label for="parentId" class="form-label">附属部门</label>
              <input type="text" class="form-control" id="parentId" name="parentId" required />
            </div>
            <div class="mb-3">
              <label for="name" class="form-label">部门名称</label>
              <input type="text" class="form-control" id="name" name="name" required />
            </div>
            <div class="mb-3">
              <label for="type" class="form-label">部门类型</label>
              <input type="text" class="form-control" id="type" name="type" required />
            </div>
            <div class="mb-3">
              <label for="phone" class="form-label">手机号码</label>
              <input type="text" class="form-control" id="phone" name="phone" />
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            <button type="submit" class="btn btn-primary">提交</button>
          </div>
          <span class="label label-danger">提交后 数据更改正常，但是无法正常关闭模拟框，只能刷新页面</span>
        </div>
      </div>
    </form>
  </div>

  <!-- Vendor JS Files -->
  <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="assets/vendor/gridjs/dist/gridjs.umd.js"></script>
  <script src="assets/vendor/moment/moment.js"></script>

  <!-- 手动定义中文本地化配置 -->
  <script>
    const cnCN = {
      search: {
        placeholder: '搜索...'
      },
      pagination: {
        previous: '上一页',
        next: '下一页',
        showing: '显示',
        results: () => '条结果'
      },
      loading: '加载中...',
      noRecordsFound: '没有找到匹配的记录',
      error: '加载数据时发生错误',
    };
  </script>

  <!-- Page-Specific JS -->
  <script>
    const url = "/api/rest/dept/all";
    let depts = [];

    const columns = [
      { id: "name", name: "部门名称" },
      { id: "id", name: "编号", width: "10%" },
      { id: "enableState", name: "状态" },
      { id: "type", name: "类型" },
      { id: "phone", name: "电话" },
      { id: "createAt", name: "创建时间" },
      {
        name: "操作",
        width: "20%",
        formatter: (_, row) => gridjs.html(`
          <button class="updateDeptButton btn btn-sm btn-primary m-1" data-id="${row.cells[1].data}">
            <i class="bi bi-pencil-square"></i> 编辑
          </button>
        <button class="toggleDeptButton btn btn-sm btn-warning m-1" data-id="${row.cells[1].data}">
  <i class="${row.cells[2].data === '启用' ? 'bi bi-check-lg text-success' : 'bi bi-x-lg text-danger'}"></i> ${row.cells[2].data === "启用" ? "禁用" : "启用"}
</button>
        `),
      },
    ];

    const gridOptions = {
      columns,
      server: {
        url,
        then: data => {
          depts = data;
          return data.map(item => [
            item.name,
            item.id,
            item.enableState,
            item.type,
            item.phone,
            item.createAt ? moment(item.createAt).format("YYYY-MM-DD HH:mm:ss") : ""
          ]);
        },
        total: data => data.totalElements,
      },
      pagination: true,
      language: cnCN,  // 使用手动定义的中文本地化
    };

    window.onload = function () {
      const grid = new gridjs.Grid(gridOptions).render(document.getElementById("dataTable"));

      // 查询表单的提交事件监听器
      document.getElementById("searchForm").addEventListener("submit", async (event) => {
        event.preventDefault(); // 阻止默认提交行为

        // 初始化表单数据
        const formData = new FormData(document.getElementById("searchForm"));
        const name = formData.get("name").trim();
        const enableState = formData.get("enableState");
        const type = formData.get("type");

        try {
          // 发送 GET 请求获取数据
          const response = await fetch(url); // 使用全局定义的 `url` 进行请求
          const data = await response.json();

          // 根据查询条件过滤数据
          let filteredData = data.filter(item => {
            return (
              (!name || item.name.includes(name)) &&
              (!enableState || item.enableState === enableState) &&
              (!type || item.type === type)
            );
          });

          // 包装过滤后的数据以符合 gridjs 的结构
          filteredData = {
            content: filteredData,
            totalElements: filteredData.length
          };

          // 更新服务器请求的数据
          const server = {
            url, // 保留 url 为未来可能的服务器请求
            then: () => {
              return filteredData.content.map(item => [
                item.name,
                item.id,
                item.type,
                item.enableState,
                item.phone,
                item.createAt ? moment(item.createAt).format("YYYY-MM-DD HH:mm:ss") : "",
              ]);
            },
            total: () => filteredData.totalElements
          };

          // 更新表格数据并强制渲染
          grid.updateConfig({ server }).forceRender();
        } catch (error) {
          // 如果出错，打印错误信息或显示提示
          console.error("查询数据时发生错误：", error.message);
          showToastPro("查询数据时发生错误：" + error.message); // 显示错误提示
        }
      });

      // 其余代码，例如更新和状态切换等...
      document.getElementById("dataTable").addEventListener("click", (event) => {
        if (event.target.closest(".updateDeptButton")) {
          const id = event.target.closest(".updateDeptButton").getAttribute("-dataid");
          const dept = depts.find(d => d.id === id);
          if (dept) {
            document.getElementById("id").value = dept.id;
            document.getElementById("parentId").value = dept.parentId || '';
            document.getElementById("name").value = dept.name;
            document.getElementById("type").value = dept.type;
            document.getElementById("phone").value = dept.phone || '';
            new bootstrap.Modal(document.getElementById("editdeptModalEl")).show();
          }
        } else if (event.target.closest(".toggleDeptButton")) {
          const id = event.target.closest(".toggleDeptButton").getAttribute("data-id");
          fetch(`/api/rest/dept/${encodeURIComponent(id)}/toggle`, { method: "PATCH" })
            .then(response => {
              if (response.ok) {
                document.getElementById("successMessage").innerText = "切换部门状态成功！";
                new bootstrap.Toast(document.getElementById("successToastEl")).show();
                grid.updateConfig(gridOptions).forceRender();
              } else {
                console.error("请求失败：", response.statusText);
              }
            })
            .catch(error => {
              console.error("网络错误：", error);
            });
        }
      });

      // 点击“添加”按钮时清空表单并显示模态框
      document.getElementById("createdeptButton").addEventListener("click", () => {
        document.getElementById("editdeptForm").reset();
        document.getElementById("editdeptModalEl").querySelector('.modal-title').innerText = '添加部门';
        new bootstrap.Modal(document.getElementById("editdeptModalEl")).show();
      });

      // 监听编辑/添加部门表单的提交事件
      document.getElementById("editdeptForm").addEventListener("submit", (event) => {
        event.preventDefault();

        // 检查表单的有效性
        if (event.target.checkValidity()) {
          const formData = Object.fromEntries(new FormData(event.target));
          const isAdding = document.getElementById("editdeptModalEl").querySelector('.modal-title').innerText === '添加部门';

          // 根据是否为“添加”选择请求方法和URL
          const requestOptions = {
            method: isAdding ? 'POST' : 'PATCH',
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(formData),
          };
          const url = isAdding ? '/api/rest/dept' : `/api/rest/dept/${encodeURIComponent(formData.id)}`;

          fetch(url, requestOptions)
            .then(response => {
              if (response.ok) {
                new bootstrap.Modal(document.getElementById("editdeptModalEl")).hide();
                document.getElementById("successMessage").innerText = isAdding ? "部门添加成功！" : "部门更新成功！";
                new bootstrap.Toast(document.getElementById("successToastEl")).show();
                grid.updateConfig(gridOptions).forceRender(); // 刷新表格数据

              } else {
                console.error("请求失败：", response.statusText);
              }
            })
            .catch(error => {
              console.error("网络错误：", error);
            });
        } else {
          event.target.classList.add("was-validated");
        }
      });
    };


  </script>
</body>

</html>